package com.project.service.sys;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.project.common.Constants;
import com.project.common.Page;
import com.project.common.TreeNode;
import com.project.service.BaseService;
import com.project.dao.sys.PermissionsDao;
import com.project.dao.sys.RoleDao;
import com.project.entity.sys.Permissions;
import com.project.entity.sys.Role;
import com.project.entity.sys.User;
import com.project.util.CurrentSessionUtil;
import com.project.util.GenerateCode;
import com.project.util.JacksonUtil;
import com.project.util.ListUtil;

/**
 * 角色service
 * @author
 *
 */
@Transactional
@Service
public class RoleService extends BaseService<Role>{

	@Autowired
	private RoleDao roleDao;
	
	@Autowired
	private PermissionsDao permissionsDao;
	
	@Autowired
	private SysLogService sysLogService;
	
	
	/**
	 * 新建角色
	 * @param role
	 */
	public void save(Role role,String permissionIds){
//		role.setStatus(Constants.STATUS_OPEN);//默认开启状态
		role.setCreateUser(CurrentSessionUtil.getCurrentUser().getUserCode());
		role.setCreateTime(new Date());
		role.setUpdateUser(CurrentSessionUtil.getCurrentUser().getUserCode());
		role.setUpdateTime(new Date());
		role.setRoleCode(GenerateCode.randomWord(10, null));
		
		if(StringUtils.isNotEmpty(permissionIds)){
			List<Permissions> listPermissions = new ArrayList<Permissions>();
			for(String id : permissionIds.split(",")){
				Permissions permissions = permissionsDao.getById(Long.parseLong(id));
				listPermissions.add(permissions);
			}
			
			role.setPermissions(listPermissions);
		}
		
		roleDao.saveOrUpdate(role);
		
		/*日志*/
		sysLogService.save("add", "role", role.getId(), "角色管理-新增角色", "新增角色", "新增角色“"+role.getRoleName()+"”");
	}
	
	/**
	 * 修改角色
	 * @param role
	 * @param permissionIds
	 */
	public void update(Role role,String permissionIds){
		role.setUpdateUser(CurrentSessionUtil.getCurrentUser().getUserCode());
		role.setUpdateTime(new Date());
		
		List<Permissions> listPermissions = new ArrayList<Permissions>();
		if(StringUtils.isNotEmpty(permissionIds)){
			for(String id : permissionIds.split(",")){
				Permissions permissions = permissionsDao.getById(Long.parseLong(id));
				listPermissions.add(permissions);
			}
			
		}
		role.setPermissions(listPermissions);
		
		roleDao.saveOrUpdate(role);
		
		/*日志*/
		sysLogService.save("update", "role", role.getId(), "角色管理-修改角色", "修改角色", "角色“"+role.getRoleName()+"”已修改");
	}
	
	/**
	 * 分页查询角色
	 * @param page
	 * @return
	 */
	public Page<Role> queryRolePage(Page<Role> page){
		return roleDao.queryPage(page);
	}
	
	/**
	 * 获取所有权限
	 * @return
	 */
	public String queryPermissionsTree()throws Exception{
		List<Permissions> permissionsList = permissionsDao.getAll(Constants.STATUS_OPEN);
		List<TreeNode> treeNodeList = new ArrayList<TreeNode>();
		
		for(Permissions entity :permissionsList){
			TreeNode treeNode = new TreeNode(String.valueOf(entity.getId()), 
											 entity.getParentId()==null ? "":String.valueOf(entity.getParentId()), 
											 entity.getPermissionsName(), 
											 false, 
											 true,
											 false,
											 "");
			treeNodeList.add(treeNode);
		}
		
		return JacksonUtil.objToJson(treeNodeList);
	}
	
	/**
	 * 获取当前角色勾选的数据 
	 * @param roleId
	 * @return
	 */
	public String getRolesPermissions(Role role,String status)throws Exception{
		List<Permissions> allPermissions = permissionsDao.getAll(Constants.STATUS_OPEN);
		List<Permissions> rolesPermissions = role.getPermissions();
		List<TreeNode> treeNodes = new ArrayList<TreeNode>();
		
		/*将当权限勾践成TreeNode格式，并且将当前role所拥有的权限默认选中*/
		for(Permissions fullP:allPermissions){
			TreeNode treeNode = new TreeNode();
			
			boolean flag = false;
			for(Permissions roelsP:rolesPermissions){
				
				if(fullP.getId().equals(roelsP.getId())){
					flag = true;
					break;
				}else{
					flag = false;
				}
				
			}
			
			treeNode.setId(String.valueOf(fullP.getId()));
			treeNode.setpId(fullP.getParentId()==null ? "":String.valueOf(fullP.getParentId()));
			treeNode.setName(fullP.getPermissionsName());
			treeNode.setChecked(flag);
			treeNode.setOpen(true);
			
			if("view".equals(status)){
				treeNode.setChkDisabled(true);
			}else if("update".equals(status)){
				treeNode.setChkDisabled(false);
			}
			
			treeNodes.add(treeNode);
		}
		
		
		return JacksonUtil.objToJson(treeNodes);
	}
	
	/**
	 * 查询是否存在
	 * @param roleName
	 * @param type
	 * @return
	 */
	public String getStatus(String roleName,String type,String id){
		Role role = null;
		
		if("1".equals(type)){//更新时查询是否重复，不包含本身
			role = roleDao.getByIdAnName(Long.parseLong(id), roleName);
		}else{//默认为全表查询
			role = roleDao.getByName(roleName);
		}
		
		
		if(role != null){
			return "1";
		}else{
			return "0";
		}
		
	}
	
	/**
	 * 获取所有启用的角色
	 * @return
	 */
	@Cacheable(value="allRole")
	public List<Role> queryList(){
		return roleDao.queryRolesByStatus(Constants.STATUS_OPEN);
	}
	
	/**
	 * 获取所有可用的权限
	 * @return
	 */
	@Cacheable(value="allPermissions")
	public List<Permissions> getAllPermissions(){
		return permissionsDao.getAll(Constants.STATUS_OPEN);
	}
	
	/**
	 * 查询当前用户的所有角色
	 * @param userCode
	 * @return
	 */
	@Cacheable(value="queryRoleList")
	public List<Map<String,Object>> queryRoleList(String userCode){
		return roleDao.queryList(userCode);
	}
	
	/**
	 * 查询是否可以删除
	 * @param id
	 * @return
	 */
	public boolean whetherCanDelete(Long id){
		Role role = roleDao.getById(id);
		if(role != null){
			List<User> list = role.getUsers();
			if(ListUtil.isNotEmpty(list)){
				return false;
			}else{
				return true;
			}
		}else{
			return false;
		}
	}
	
	/**
	 * 删除角色
	 * @param role
	 */
	public void delete(Role role)throws Exception{
		roleDao.delete(role);
		
		/*日志*/
		sysLogService.save("delete", "role", role.getId(), "角色管理-删除角色", "删除角色", "角色“"+role.getRoleName()+"”已经删除");
	}
	
	/**
	 * 启用禁用
	 * @param user
	 * @param status
	 */
	public void doEd(Role role, String status){
		role.setStatus(status);
		role.setUpdateUser(CurrentSessionUtil.getCurrentUser().getUserCode());
		role.setUpdateTime(new Date());
		
		roleDao.update(role);
		
		String str = "";
		if(Constants.STATUS_CLOSE.equals(status)){
			str = "禁用";
		}else if(Constants.STATUS_OPEN.equals(status)){
			str = "启用";
		}
		
		/*日志*/
		sysLogService.save("delete", "role", role.getId(), "角色管理-"+str+"角色", str+"角色", "角色“"+role.getRoleName()+"”已经"+str);
	}
}
